<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1000px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" :clearable="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房号" prop="number">
            <el-input v-model="formData.number" placeholder="请输入房号" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="请输入类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.OFFICE_SPACE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="办公楼" prop="building.name">
            <el-input
              v-model="formData.building.name"
              :clearable="true"
              :disabled="true"
              class="mr-1"
            />
            <el-button @click="clickChooseBuilding">选择办公楼</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="办公楼单元" prop="buildingUnitId">
            <el-select v-model="formData.buildingUnitId" placeholder="请选择办公楼单元">
              <el-option
                v-for="dict in buildingUnitList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="办公楼楼层" prop="buildingFloorId">
            <el-select v-model="formData.buildingFloorId" placeholder="请选择办公楼楼层">
              <el-option
                v-for="dict in buildingFloorList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位" prop="unitId">
            <el-select v-model="formData.unitId" placeholder="请选择单位">
              <el-option
                v-for="dict in unitList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="面积" prop="area">
            <InputNumber type="decimal" v-model="formData.area" placeholder="请输入面积" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入备注"
              :clearable="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddWorker">添加办公人员</el-button>
      <el-button @click="clickDeleteWorker">删除办公人员</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.spaceWorkers"
      save-key="OfficeSpaceEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    />
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <OfficeBuildingSelect ref="buildingSelectRef" @select-value="handleSelectBuilding" />
  <UnitWorkerSelect ref="workerSelectRef" @select-value="handleSelectWorker" />
</template>
<script setup name="OfficeSpaceEdit" lang="ts">
import * as OfficeSpaceModel from '@/model/office/space/OfficeSpace'
import * as OfficeSpaceWorkerModel from '@/model/office/space/OfficeSpaceWorker'
import OfficeBuildingSelect from '../officeBuilding/OfficeBuildingSelect.vue'
import UnitWorkerSelect from '@/views/unit/worker/UnitWorkerSelect.vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as UnitApi from '@/api/unit/unit'
import * as OfficeSpaceApi from '@/api/office/space'
import * as OfficeBuildingApi from '@/api/office/building'
import { getKeyList } from '@pureadmin/utils'
interface OfficeSpaceWorkerEdit extends OfficeSpaceWorkerModel.OfficeSpaceWorker {
  worker: {
    name: string
    rank: {
      name: string
      area: number
    }
  }
  operateType: string
}
interface OfficeSpaceEdit extends OfficeSpaceModel.OfficeSpace {
  building: { name: string }
  spaceWorkers: OfficeSpaceWorkerEdit[]
}
const buildingSelectRef = ref()
const workerSelectRef = ref()
const buildingFloorList = ref()
const buildingUnitList = ref()
const unitList = ref()
const message = useMessage()
const { t } = useI18n()
let formType = ''
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<OfficeSpaceEdit>({
  id: undefined,
  name: '',
  building: { name: '' },
  number: '',
  type: 1,
  buildingId: undefined,
  buildingUnitId: undefined,
  buildingFloorId: undefined,
  unitId: undefined,
  area: 0,
  remark: '',
  status: 1,
  spaceWorkers: []
})
const formRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  'building.name': [{ required: true, message: '请选择办公楼', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '姓名',
    prop: 'worker.name'
  },
  {
    label: '职级',
    prop: 'worker.rank.name'
  },
  {
    label: '标准面积',
    prop: 'worker.rank.area'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  unitList.value = await UnitApi.simpleList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await OfficeSpaceApi.singleGet(id)
      if (data.buildingId != undefined) {
        buildingFloorList.value = await OfficeBuildingApi.simpleFloorGet(data.buildingId)
        buildingUnitList.value = await OfficeBuildingApi.simpleUnitGet(data.buildingId)
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    building: { name: '' },
    number: '',
    type: 1,
    buildingId: undefined,
    buildingUnitId: undefined,
    buildingFloorId: undefined,
    unitId: undefined,
    area: 0,
    remark: '',
    status: 1,
    spaceWorkers: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OfficeSpaceEdit
    if (formType === 'create') {
      await OfficeSpaceApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await OfficeSpaceApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const handleSelectBuilding = async (officeBuildingInfo) => {
  formData.value.buildingId = officeBuildingInfo.id
  formData.value.building.name = officeBuildingInfo.name
  buildingFloorList.value = await OfficeBuildingApi.simpleFloorGet(officeBuildingInfo.id)
  buildingUnitList.value = await OfficeBuildingApi.simpleUnitGet(officeBuildingInfo.id)
}

const handleSelectWorker = (workerInfoList) => {
  const workerIds = getKeyList(formData.value.spaceWorkers, 'workerId')
  workerInfoList.forEach((worker) => {
    if (workerIds.indexOf(worker.id) < 0) {
      formData.value.spaceWorkers.push({
        id: undefined,
        spaceId: formType === 'create' ? undefined : formData.value.id,
        workerId: worker.id,
        worker: {
          name: worker.name,
          rank: {
            name: worker.rank.name,
            area: worker.rank.area
          }
        },
        operateType: 'new'
      })
    }
  })
}

const clickChooseBuilding = () => {
  buildingSelectRef.value.open()
}

const clickAddWorker = () => {
  workerSelectRef.value.open(formData.value.unitId)
}

const clickDeleteWorker = () => {
  if (formType === 'create' || tableCurrentRow.value.id == undefined) {
    const index = formData.value.spaceWorkers.indexOf(tableCurrentRow.value)
    formData.value.spaceWorkers.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}
</script>
